#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/9/23 11:45
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import datetime
import math
import threading
import time
import random
import traceback
from urllib import parse

import requests

from auto_battle_room import YamlControl, init_login
from user_info import batch_add_balance


class AutoOpenCase:
    def __init__(self):
        yaml_control_user = YamlControl("/data/dream_user_info.yaml")
        self.user_info = yaml_control_user.read_yaml()["user_info1"]
        self.config_data = YamlControl("/data/config.yaml").read_yaml()  # 读取配置项
        self.host = self.config_data["host"]  # 获取环境域名

    def get_box_list(self):
        """
        获取箱子列表
        :return:
        """
        url = "/api/case/getCaseList"
        headers = {
            "Token": self.user_info[0]["token"]
        }
        data = {
            "moduleId": 5,
            "themeId": -1
        }
        box_info = requests.get(url=self.host + url, params=data, headers=headers).json()["data"]
        box_list = []
        for box_theme in box_info:
            for box in box_theme["boxList"]:
                box_list.append(box["id"])
        return box_list

    def get_hot_box_list(self):
        """
        获取热门箱子列表
        """
        url = "/api/case/getTopCaseList"
        headers = {
            "Token": self.user_info[0]["token"]
        }
        hot_box_info = requests.get(url=self.host + url, headers=headers).json()["data"]
        hot_box_list = []
        for box in hot_box_info["boxList"]:
            hot_box_list.append(box["id"])
        return hot_box_list

    def get_all_case_list(self):
        """
        获取所有箱子列表
        """
        try:
            hot_box_list = self.get_hot_box_list()
            box_list = self.get_box_list()
            all_case_list = hot_box_list + box_list
            return all_case_list
        except Exception as e:
            traceback.print_exc()
            return []

    def get_dream_gift(self, dream_gift_max_price):
        """
        获取随机追梦饰品
        :return:
        """
        url = "/api/upgrade/page"
        headers = {
            "Token": self.user_info[0]["token"]
        }
        data = {
            "page": 1,
            "pageSize": 600,
            "orderByPrice": True
        }
        dream_gift_info = requests.get(url=self.host + url, params=data, headers=headers).json()["data"]["pageData"]
        dream_gift_list = []
        for dream_gift in dream_gift_info:
            if dream_gift["recoveryPrice"] <= dream_gift_max_price:
                dream_gift_list.append({"gift_id": dream_gift["id"], "gift_price": dream_gift["recoveryPrice"]})
        return dream_gift_list

    def get_dream_config(self):
        """
        获取追梦配置
        :return:
        """
        url = "/api/upgrade/config"
        headers = {
            "Token": self.user_info[0]["token"]
        }
        dream_config = requests.get(url=self.host + url, headers=headers).json()["data"]
        return dream_config

    def open_case(self, box_id, token):
        """
        开箱子
        """
        url = "/api/case/openCase"
        data = {
            "boxId": box_id,
            "number": random.randint(1, 2)
        }
        headers = {
            "Token": token,
        }
        response = requests.get(url=self.host + url, params=data, headers=headers)
        return response

    def dream(self, dream_gift, token):
        """
        追梦
        :return:
        """
        url = "/api/upgrade/start"
        headers = {
            "Token": token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        # 在[1, 100]随机生成max和min两个整数，其中max>min，max和min的差值不能超过75，max和min的差值不能小于5
        _a = random.randint(1, 99)
        _b = random.randint(1, 99)
        roll_high = max(_a, _b)
        roll_low = min(_a, _b)
        while roll_high - roll_low > 75 or roll_high - roll_low < 5:
            _a = random.randint(1, 99)
            _b = random.randint(1, 99)
            roll_high = max(_a, _b)
            roll_low = min(_a, _b)

        reward_rate = self.get_dream_config()["returnRate"]
        quantity_init = dream_gift["gift_price"] * (roll_high - roll_low) / 100 / reward_rate
        # 使用 math.ceil() 向上取整并保留两位小数
        quantity = math.ceil(quantity_init * 100) / 100
        data = {
            "quantity": quantity,
            "requestRollCodeHigh": roll_high * 10000,
            "requestRollCodeLow": roll_low * 10000,
            "upgradeGiftId": dream_gift["gift_id"],
        }
        data = parse.urlencode(data)
        try:
            response = requests.post(url=self.host + url, data=data, headers=headers)
            return response
        except Exception as e:
            print(f"追梦报错：饰品为{dream_gift}，low是{roll_low}, high是{roll_high}, 价格是{quantity}")


open_case = AutoOpenCase()
user_info = open_case.user_info
# open_users1 = user_info[:int(len(user_info) / 3)]
# open_users2 = user_info[int(len(user_info) / 3):int(len(user_info) / 3) * 2]
# dream_users = user_info[int(len(user_info) / 3) * 2:]
open_users1 = user_info[:int(len(user_info) / 2)]
open_users2 = user_info[int(len(user_info) / 2):]

open_case_lists = open_case.get_all_case_list()
i = 0
while not open_case_lists:
    open_case_lists = open_case.get_all_case_list()
    if open_case_lists:
        break
    i += 1
    if i == 10:
        print(f"获取箱子列表失败{i}次, 使用默认值")
        open_case_lists = ['125', '143', '144', '124', '142', '136', '141', '139',
                           '140', '137', '126', '128', '127', '129', '130', '132',
                           '133', '134', '131', '135', '155', '149', '146', '147']
        break
time.sleep(1)


def auto_open_case(open_users):
    # now_time = time.strftime("%H:%M:%S", time.localtime())
    # print(f"{now_time}  本轮开箱工作开始啦")
    while True:
        now_time = datetime.datetime.now().strftime("%H:%M")
        if "00:40" <= now_time <= "01:30":
            break
        try:
            now_time = time.strftime("%H:%M:%S", time.localtime())
            for open_case_id in open_case_lists:
                # 1、获取用户token
                open_user = random.choice(open_users)
                token = open_user["token"]
                # 2、随机开箱子
                res_open = open_case.open_case(open_case_id, token)
                if res_open.json()["status"] == 0:
                    print(f"{now_time}  {open_user['account']}完成开箱，箱子ID为{open_case_id}")
                elif res_open.json()["status"] == 1:
                    print(f"{now_time}  开箱失败，箱子ID为{open_case_id}，用户是{open_user},原因：{res_open.json()['msg']}")
                    batch_add_balance(open_user['account'], open_user['account'])
                elif res_open.json()["status"] == 401:
                    print(f"{now_time}  开箱失败，箱子ID为{open_case_id}，用户是{open_user}, 原因：{res_open.json()['msg']}")
                    token = init_login(open_user['account'])
                    [d.update({"token": token}) for d in open_users if d["uid"] == open_user["uid"]]

                else:
                    pass
                time.sleep(random.randint(8, 12))

        except Exception as e:
            print("开箱报错")
            print(traceback.print_exc())
            time.sleep(1)
            try:
                batch_add_balance(open_user['account'], open_user['account'])  # 重新充值
                token = init_login(open_user['account'])  # 重新登陆
                [d.update({"token": token}) for d in open_users if d["uid"] == open_user["uid"]]
                continue
            except:
                continue


def auto_dream(dream_user_list):
    now_time = time.strftime("%H:%M:%S", time.localtime())
    print(f"{now_time}  本轮追梦工作开始啦")
    dream_gift_list = open_case.get_dream_gift(open_case.config_data["dream_gift_max_price"])
    while True:
        now_time = datetime.datetime.now().strftime("%H:%M")
        if "01:00" <= now_time <= "01:30":
            break
        try:
            now_time = time.strftime("%H:%M:%S", time.localtime())
            # 1、获取用户token
            dream_user = random.choice(dream_user_list)
            token = dream_user["token"]
            # 3、随机追梦
            dream_gift = random.choice(dream_gift_list)
            res_dream = open_case.dream(dream_gift, token)
            if res_dream.json()["status"] == 0:
                print(f"{now_time}  {dream_user['account']}完成追梦，饰品ID为{dream_gift['gift_id']}")
            elif res_dream.json()["status"] == 1:
                print(f"{now_time}  {dream_user}追梦失败，饰品ID为{dream_gift['gift_id']}，原因：{res_dream.json()['msg']}")
                batch_add_balance(dream_user['account'], dream_user['account'])  # 重新充值
            elif res_dream.json()["status"] == 401:
                print(f"{now_time}  {dream_user}追梦失败，饰品ID为{dream_gift['gift_id']}，,原因：{res_dream.json()['msg']}")
                token = init_login(account=dream_user['account'])  # 重新登陆
                [d.update({"token": token}) for d in dream_user_list if d["account"] == dream_user["account"]]
                print()
            else:
                pass

            time.sleep(random.randint(25, 48))

        except Exception as e:
            print("追梦报错")
            print(traceback.print_exc())
            time.sleep(1)
            try:
                batch_add_balance(phone1=dream_user['account'], phone2=dream_user['account'])  # 重新充值
                # init_login(account=dream_user['account'])  # 重新登陆
                token = init_login(account=dream_user['account'])  # 重新登陆
                [d.update({"token": token}) for d in dream_user_list if d["account"] == dream_user["account"]]
                continue
            except:
                continue


# 创建线程
t1 = threading.Thread(target=lambda: auto_dream(user_info))
t2 = threading.Thread(target=lambda: auto_open_case(open_users1))
t3 = threading.Thread(target=lambda: auto_open_case(open_users2))

# 启动线程
t1.start()
t2.start()
t3.start()

# 等程序结束
t1.join()
t2.join()
t3.join()

now = datetime.datetime.now()
end_time = now.strftime("%Y-%m-%d %H:%M:%S")

print("本轮roll工作到此结束啦")
print(f"end time: {end_time}")


if __name__ == '__main__':
    pass
    # open_cases = AutoOpenCase()
    # a = open_cases.get_dream_gift(4000)
    # print(a)
    # print(len(a))
